package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threablocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;


/**
 * @作者 itcast
 * @创建日期 2021/7/15 14:24
 **/
@Service
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        //1. 校验参数 (校验框架负责 )
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2. 先查询行为实体数据
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if(apBehaviorEntry == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"查询关联行为实体失败");
        }

        //3. 如果是 点赞操作，并且点赞已存在  提示请勿重复点赞
        Short operation = dto.getOperation();
        Query query = Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId())
                .and("articleId").is(dto.getArticleId()));
        if(operation.intValue() == 0){
            // 根据行为实体id  +  文章id 查询是否点赞
            ApLikesBehavior likesBehavior = mongoTemplate.findOne(query, ApLikesBehavior.class);
            if (likesBehavior !=null) {
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"请勿重复点赞");
            }
            likesBehavior = new ApLikesBehavior();
            likesBehavior.setEntryId(apBehaviorEntry.getId());
            likesBehavior.setArticleId(dto.getArticleId());
            likesBehavior.setType((short)0);
            likesBehavior.setOperation((short)0);
            likesBehavior.setCreatedTime(new Date());
            mongoTemplate.save(likesBehavior);
        }else {
            mongoTemplate.remove(query,ApLikesBehavior.class);
        }
        return ResponseResult.okResult();
    }
}
